<template>
  <div class="container">
    <div class="header">
      <h2>患者聊天中心</h2>
      <p>{{ lhxCurrentUser.name }} ({{ lhxCurrentUser.userId }})</p>
    </div>
    
    <!-- Tab导航 -->
    <div class="tabs">
      <button :class="{ active: lhxActiveTab === 'chats' }" @click="lhxActiveTab = 'chats'">
        聊天列表
      </button>
      <button :class="{ active: lhxActiveTab === 'start' }" @click="lhxActiveTab = 'start'">
        发起聊天
      </button>
    </div>
    
    <!-- 聊天列表 -->
    <div v-if="lhxActiveTab === 'chats'">
      <div v-if="lhxLoading">加载中...</div>
      <div v-else-if="lhxError">{{ lhxError }}</div>
      <div v-else>
        <div v-if="lhxDoctors.length === 0">暂无聊天记录</div>
        <div 
          v-for="chat in lhxDoctors" 
          :key="chat.roomId"
          class="chat-item"
          @click="lhxOpenChat(chat)"
        >
          <div>
            <strong>{{ chat.doctor.name }}</strong>
            <span>{{ chat.doctor.department }}</span>
          </div>
          <div>{{ chat.lastMessage.content }}</div>
          <div v-if="chat.unreadCount > 0" class="unread">{{ chat.unreadCount }}</div>
        </div>
      </div>
    </div>
    
    <!-- 发起聊天 -->
    <div v-if="lhxActiveTab === 'start'">
      <LhxDoctorSelection :currentUser="lhxCurrentUser" />
    </div>

    <!-- 底部导航栏 -->
    <div class="tabbar-new">
      <div
        v-for="(tab, idx) in tabbar"
        :key="tab.icon"
        :class="['tabbar-item', { active: tab.icon === 'bell' }]"
        @click="handleTabClick(tab.icon)"
      >
        <span class="icon-wrap">
          <svg v-if="tab.icon === 'home'" width="28" height="28" viewBox="0 0 24 24" fill="none" :stroke="tab.icon === 'home' ? '#1877F2' : '#555'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M3 11.5L12 4l9 7.5V20a1 1 0 0 1-1 1h-4a1 1 0 0 1-1-1v-4h-2v4a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V11.5z"/>
          </svg>
          <svg v-else-if="tab.icon === 'msg'" width="28" height="28" viewBox="0 0 24 24" fill="none" :stroke="tab.icon === 'msg' ? '#1877F2' : '#555'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
          </svg>
          <svg v-else-if="tab.icon === 'calendar'" width="28" height="28" viewBox="0 0 24 24" fill="none" :stroke="tab.icon === 'calendar' ? '#1877F2' : '#555'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <rect x="3" y="4" width="18" height="18" rx="4"/>
            <path d="M16 2v4M8 2v4M3 10h18"/>
          </svg>
          <span v-else-if="tab.icon === 'bell'" class="icon-bell-wrap">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" :stroke="tab.icon === 'bell' ? '#1877F2' : '#555'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M18 16v-5a6 6 0 0 0-12 0v5a2 2 0 0 1-2 2h16a2 2 0 0 1-2-2z"/>
              <path d="M13.73 21a2 2 0 0 1-3.46 0"/>
            </svg>
            <span class="dot"></span>
          </span>
          <svg v-else-if="tab.icon === 'user'" width="28" height="28" viewBox="0 0 24 24" fill="none" :stroke="tab.icon === 'user' ? '#1877F2' : '#555'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="12" cy="8" r="4"/>
            <path d="M4 20v-1a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v1"/>
          </svg>
        </span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import LhxDoctorSelection from './LhxDoctorSelection.vue';

const router = useRouter();

const lhxLoading = ref(false);
const lhxError = ref('');
const lhxDoctors = ref<any[]>([]);
const lhxActiveTab = ref('chats');

const lhxCurrentUser = ref((() => {
  try {
    const stored = localStorage.getItem('lhx_current_user');
    return stored ? JSON.parse(stored) : { userId: 'p001', name: '患者张三', userType: 'patient' };
  } catch {
    return { userId: 'p001', name: '患者张三', userType: 'patient' };
  }
})());

const tabbar = [
  { icon: 'home' },
  { icon: 'msg' },
  { icon: 'calendar' },
  { icon: 'bell' },
  { icon: 'user' },
]

function handleTabClick(icon: string) {
  switch (icon) {
    case 'home':
      router.push('/home');
      break;
    case 'msg':
      router.push('/zxl');
      break;
    case 'calendar':
      router.push('/time-select');
      break;
    case 'bell':
      // 当前页面（聊天）
      break;
    case 'user':
      router.push('/medical-home');
      break;
  }
}

async function lhxLoadChats() {
  lhxLoading.value = true;
  try {
    const response = await fetch(`http://localhost:3000/lhx/patient/${lhxCurrentUser.value.userId}/chats`);
    const result = await response.json();
    if (result.success) {
      lhxDoctors.value = result.data;
    } else {
      lhxError.value = result.message;
    }
  } catch {
    lhxError.value = '网络错误';
  }
  lhxLoading.value = false;
}

function lhxOpenChat(chat: any) {
  router.push({
    path: '/lhx-chat',
    query: {
      lhxRoomId: chat.roomId,
      lhxDoctorId: chat.doctor.userId,
      lhxDoctorName: chat.doctor.name,
      lhxUserId: lhxCurrentUser.value.userId,
      lhxUserType: lhxCurrentUser.value.userType,
      lhxUserName: lhxCurrentUser.value.name
    }
  });
}

onMounted(() => {
  if (lhxActiveTab.value === 'chats') {
    lhxLoadChats();
  }
});
</script>

<style scoped>
.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  padding-bottom: 88px;
}

.header {
  text-align: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
}

.tabs {
  display: flex;
  margin-bottom: 20px;
}

.tabs button {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
}

.tabs button.active {
  background: #3498db;
  color: white;
}

.chat-item {
  padding: 15px;
  border: 1px solid #eee;
  margin-bottom: 10px;
  cursor: pointer;
  background: white;
}

.chat-item:hover {
  background: #f9f9f9;
}

.unread {
  background: #e74c3c;
  color: white;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 12px;
}

.tabbar-new {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 16px;
  margin: 0 auto;
  width: 92vw;
  max-width: 420px;
  height: 56px;
  background: #fff;
  border-radius: 28px;
  box-shadow: 0 2px 16px 0 rgba(24,119,242,0.08);
  display: flex;
  justify-content: space-around;
  align-items: center;
  z-index: 100;
}

.tabbar-new .tabbar-item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  height: 100%;
  cursor: pointer;
  transition: color 0.2s;
}

.tabbar-new .tabbar-item.active svg {
  stroke: #1877F2;
}

.icon-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.icon-bell-wrap {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-bell-wrap .dot {
  position: absolute;
  top: 2px;
  right: 2px;
  width: 8px;
  height: 8px;
  background: #ff4d4f;
  border-radius: 50%;
  border: 2px solid #fff;
}
</style>